#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pandas as pd
import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 

# 1.6 分布(Distribution)

# 1.6.1 连续变量的直方图(Histogram for Continuous Variable)
# 直方图显示给定变量的频率分布. 
# 下面的图表示基于类型变量对频率条进行分组,从而更好地了解连续变量和类型变量.
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Prepare data
x_var = 'displ'
groupby_var = 'class'
df_agg = df.loc[:,[x_var,groupby_var]].groupby(groupby_var)
vals = [df[x_var].values.tolist() for i,df in df_agg]

# Draw 
plt.figure(figsize=(16,9),dpi=80)
colors = [plt.cm.Spectral(i/float(len(vals)-1)) for i in range(len(vals))]
n,bins,patches = plt.hist(vals,30,stacked=True,density=False,color=colors[:len(vals)])

# Decoration
plt.legend({group:col for group,col in zip(np.unique(df[groupby_var]).tolist(),colors[:len(vals)])})
plt.title(f"Stacked Histogram of ${x_var}$ colored by ${groupby_var}$",fontsize=22)
plt.xlabel(x_var)
plt.ylabel("Frequency")
plt.ylim(0,25)
plt.xticks(ticks=bins[::3],labels=[round(b,1) for b in bins[::3]])
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\HistogramforContinuousVariable.png")
plt.show()
"""


# 1.6.2 类型变量的直方图(Histogram for Categorical Variable)
# 类型变量的直方图显示该变量的频率分布. 通过对条形图进行着色,可以将分布与表示颜色的另一个类型变量相关联.
"""
# Import Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Prepare data
x_var = 'manufacturer'
groupby_var = 'class'
df_agg = df.loc[:,[x_var,groupby_var]].groupby(groupby_var)
vals = [df[x_var].values.tolist() for i, df in df_agg]

# Draw 
plt.figure(figsize=(16,9),dpi=80)
colors = [plt.cm.Spectral(i/float(len(vals)-1)) for i in range(len(vals))]
n,bins,patches = plt.hist(vals,df[x_var].unique().__len__(),stacked=True,density=False,color=colors[:len(vals)])

# Decoration
plt.legend({group:col for group, col in zip(np.unique(df[groupby_var]).tolist(),colors[:len(vals)])})
plt.title(f"Stacked Histogram of ${x_var}$ colored by ${groupby_var}$",fontsize=22)
plt.xlabel(x_var)
plt.ylabel("Frequency")
plt.ylim(0,40)
plt.xticks(ticks=bins,labels=np.unique(df[x_var]).tolist(),rotation=90,horizontalalignment='left')
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\HistogramforCategoricalVariable.png")
plt.show()
"""


# 1.6.3 密度图(Density Plot)
# 密度图是一种常用工具,用于可视化连续变量的分布. 通过"响应"变量对它们进行分组,可检查X和Y之间的关系.
# 以下情况用于表示目的,以描述城市里程的分布如何随着汽缸数的变化而变化.
"""
# Import Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Draw Plot
plt.figure(figsize=(16,10),dpi=80)
sns.kdeplot(df.loc[df['cyl'] == 4, "cty"],shade=True,color="g",label="Cyl=4",alpha=.7)
sns.kdeplot(df.loc[df['cyl'] == 5, "cty"],shade=True,color="deeppink",label="Cyl=5",alpha=.7)
sns.kdeplot(df.loc[df['cyl'] == 6,"cty"],shade=True,color="dodgerblue",label="Cyl=6",alpha=.7)
sns.kdeplot(df.loc[df['cyl'] == 8,"cty"],shade=True,color="orange",label="Cyl=8",alpha=.7)

# Decoration
plt.title('Density Plot of City Mileage by n_Cylinders',fontsize=22)
plt.legend()
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DensityPlot.png")
plt.show()
"""





# 1.6.4 直方密度线图(Density Curves with Histogram)
# 带有直方图的密度曲线汇集了两个图所传达的集体信息,可以将它们放在一个图中.
"""
# Import Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Draw Plot
plt.figure(figsize=(13,10),dpi=80)
sns.distplot(df.loc[df['class'] == 'compact',"cty"],color="dodgerblue",label="Compact",hist_kws={'alpha':.7},kde_kws={'linewidth':3})
sns.distplot(df.loc[df['class'] == 'suv',"cty"],color="orange",label="SUV",hist_kws={'alpha':.7},kde_kws={'linewidth':3})
sns.distplot(df.loc[df['class'] == 'minivan',"cty"],color="g",label="minivan",hist_kws={'alpha':.7},kde_kws={'linewidth':3})
plt.ylim(0,0.35)

# Decoration
plt.title('Density Plot of City Mileage by Vehicle Type', fontsize=22)
plt.legend()
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DensityCurveswithHistogram.png")
plt.show()
"""




# 1.6.5 Joy Plot
# 允许不同组的密度曲线重叠,这是一种可视化大量分组数据的彼此关系分布的好方法.使用基于matplotlib的joypy包青松构建.
# # ! pip install joypy
# """
import pandas as pd 
import joypy
import matplotlib.pyplot as plt 
import matplotlib 

matplotlib.use('TkAgg')

# Import Data
mpg = pd.read_csv("F:/PythonProject/AI/Python/DataAnalysis/datasets/mpg_ggplot2.csv")
# Draw Plot
plt.figure(figsize=(16,10),dpi=80)
fig,axes = joypy.joyplot(mpg,column=['hwy','cty'],by="class",ylim='own',figsize=(14,10))

# Decoration
plt.title('Joy Plot of City and Highway Mileage by Class',fontsize=22)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\JoyPlot.png")
plt.show()
# """
"""
输出结果报错:
 UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  % get_backend())
# 解决措施: 在导入时: matplotlib.use('TkAgg')
# """



